package cn.zl.GB28181.transmit.event.response.impl;

import cn.zl.GB28181.core.Gb28181Sdp;
import cn.zl.GB28181.transmit.SIPProcessorObserver;
import cn.zl.GB28181.transmit.SIPSender;
import cn.zl.GB28181.transmit.cmd.SIPRequestHeaderProvider;
import cn.zl.GB28181.transmit.event.response.BaseSIPResponseProcessor;
import cn.zl.GB28181.utils.SipUtils;
import gov.nist.javax.sip.ResponseEventExt;
import gov.nist.javax.sip.message.SIPResponse;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sdp.SdpParseException;
import javax.sdp.SessionDescription;
import javax.sip.InvalidArgumentException;
import javax.sip.ResponseEvent;
import javax.sip.SipException;
import javax.sip.SipFactory;
import javax.sip.address.SipURI;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.text.ParseException;

@Component
public class InviteResponseProcessor extends BaseSIPResponseProcessor {

    private static final Logger logger = LoggerFactory.getLogger(InviteResponseProcessor.class);

    private static final String method = "INVITE";

    @Resource
    private SIPProcessorObserver sipProcessorObserver;
    @Resource
    private SIPSender sipSender;
    @Resource
    private SIPRequestHeaderProvider headerProvider;

    @Override
    public void process(ResponseEvent evt) {
        logger.debug("接收到消息：{}", evt.getResponse());
        try {
            SIPResponse response = (SIPResponse)evt.getResponse();
            int statusCode = response.getStatusCode();
            // 成功响应
            // 下发ack
            if (statusCode == Response.OK) {
                ResponseEventExt event = (ResponseEventExt)evt;

                String contentString = new String(response.getRawContent());
                Gb28181Sdp gb28181Sdp = SipUtils.parseSDP(contentString);
                SessionDescription sdp = gb28181Sdp.getBaseSdb();
                SipURI requestUri = SipFactory.getInstance().createAddressFactory().createSipURI(sdp.getOrigin().getUsername(), event.getRemoteIpAddress() + ":" + event.getRemotePort());
                Request reqAck = headerProvider.createAckRequest(response.getLocalAddress().getHostAddress(), requestUri, response);

                logger.info("[回复ack] {}-> {}:{} ", sdp.getOrigin().getUsername(), event.getRemoteIpAddress(), event.getRemotePort());
                sipSender.transmitRequest( response.getLocalAddress().getHostAddress(), reqAck);
            }
        } catch (InvalidArgumentException | ParseException | SipException | SdpParseException e) {
            logger.info("[点播回复ACK]，异常：", e );
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 添加消息处理的订阅
        sipProcessorObserver.addResponseProcessor(method, this);
    }

}
